// -----------------------------------------------------------------------
//  <copyright file="PopupHelper.cs" company="OSharp开源团队">
//      Copyright (c) 2014-2020 OSharp. All rights reserved.
//  </copyright>
//  <site>http://www.osharp.org</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2020-10-09 1:58</last-date>
// -----------------------------------------------------------------------

namespace OSharp.Wpf.Xaml;

public class PopupHelper
{
    public static DependencyObject GetPopupPlacementTarget(DependencyObject obj)
    {
        return (DependencyObject)obj.GetValue(PopupPlacementTargetProperty);
    }

    public static void SetPopupPlacementTarget(DependencyObject obj, DependencyObject value)
    {
        obj.SetValue(PopupPlacementTargetProperty, value);
    }

    // Using a DependencyProperty as the backing store for PopupPlacementTarget.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty PopupPlacementTargetProperty =
        DependencyProperty.RegisterAttached("PopupPlacementTarget", typeof(DependencyObject), typeof(PopupHelper), new PropertyMetadata(null, OnPopupPlacementTargetChanged));

    private static void OnPopupPlacementTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue != null)
        {
            DependencyObject popupPopupPlacementTarget = e.NewValue as DependencyObject;
            Popup pop = d as Popup;
            if (popupPopupPlacementTarget == null || pop == null)
            {
                return;
            }

            Window win = Window.GetWindow(popupPopupPlacementTarget) ?? Application.Current.MainWindow;
            if (null != win)
            {
                win.LocationChanged += delegate
                {
                    var offset = pop.HorizontalOffset;
                    pop.HorizontalOffset = offset + 1;
                    pop.HorizontalOffset = offset;
                };
            }
        }
    }
}
